package com.example.spring5.ms;

/**
 * 蚂蚁金服：启动两个线程, 一个输出 1,3,5,7…99, 另一个输出 2,4,6,8…100 最后 STDOUT 中按序输出 1,2,3,4,5…100
 *
 * @Author: Hu Rui
 * @Date: 2021/11/11 20:29
 */
public class ThreadWaitNotify {
    public static void main(String[] args) throws InterruptedException {
        new Test().print();
    }

    static class Test {
        public void print() throws InterruptedException {
            new Thread(() -> {
                for (int i = 1; i < 100; i = i + 2) {
                    synchronized (this) {
                        System.out.println(i);
                        notify();
                        try {
                            this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, "奇数线程").start();
            Thread.sleep(100);

            new Thread(() -> {
                for (int i = 2; i < 101; i = i + 2) {
                    synchronized (this) {
                        try {
                            System.out.println(i);
                            notify();
                            this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, "偶数线程").start();
        }
    }
}
